package cn.stylefeng.guns.modular.rest.kstJy.controller;

import cn.stylefeng.guns.modular.basic.entity.BasicDriver;
import cn.stylefeng.guns.modular.basic.entity.BasicPrivatecar;
import cn.stylefeng.guns.modular.basic.service.BasicDriverService;
import cn.stylefeng.guns.modular.basic.service.BasicPrivatecarService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.rest.kstJy.dto.KstOrderDto;
import cn.stylefeng.guns.modular.rest.kstJy.dto.StationListRequestDto;
import cn.stylefeng.guns.modular.rest.kstJy.vo.CreateOrderVO;
import cn.stylefeng.guns.modular.rest.kstJy.vo.StationListRequestDetailVO;
import cn.stylefeng.guns.modular.rest.kstJy.vo.StationListRequestVO;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author : like
 * @date : 2024/8/4 9:03
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/rest/kstJy")
public class restKstJyController extends BaseController {

    private static final String signKey = "QmBH5Ez86R3mmGeE"; // 密钥
    private static final String BASE_URL_STATION_LISTS = "https://oil.scsasy.com/xiaoyun/xianfei/getStationLists"; // 获取加油站列表
    private static final String BASE_URL_STATION_INFO = "https://oil.scsasy.com/xiaoyun/xianfei/getStationInfo"; // 获取加油站详情
    private static final String BASE_URL_CREATE_ORDER = "https://oil.scsasy.com/xiaoyun/xianfei/createOrder"; // 创建订单
    private static final String BASE_URL_APPLY_REFUND = "https://oil.scsasy.com/xiaoyun/xianfei/applyRefund"; // 申请退款

    @Autowired
    private BasicDriverService basicDriverService;

    @Autowired
    private UserAop userAop;

    @Autowired
    private BasicPrivatecarService basicPrivatecarService;

    /**
     * 获取加油站列表
     * @param request
     * @return
     */
    @PostMapping("/getStationLists")
    public ResponseData getStationLists(@RequestBody StationListRequestDto request) {
        // 请求体
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("longitude", request.getLongitude());
        body.add("latitude", request.getLatitude());
        body.add("page", request.getPage());
        body.add("pagesize", request.getPagesize());
        if (request.getGasName() != null) {
            body.add("gas_name", request.getGasName());
        }
        if (request.getCity() != null) {
            body.add("city", request.getCity());
        }

        return sendRequest(BASE_URL_STATION_LISTS, body, StationListRequestVO.class);
    }

    /**
     * 获取加油站详情
     * @param request
     * @return
     */
    @PostMapping("/getStationInfo")
    public ResponseData getStationInfo(@RequestBody StationListRequestDto request) {
        // 请求体
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("longitude", request.getLongitude());
        body.add("latitude", request.getLatitude());
        body.add("station_id", request.getStationId());

        return sendRequest(BASE_URL_STATION_INFO, body, StationListRequestDetailVO.class);
    }


    /**
     * 创建订单
     * @param request
     * @return
     */
    @PostMapping("/createOrder")
    public ResponseData createOrder(@RequestBody KstOrderDto request) {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("total_amount", request.getTotalAmount());
        body.add("unit_price", request.getUnitPrice());
        body.add("order_number", "123456");
        body.add("litre_num", request.getLitreNum());
        body.add("station_id", request.getStationId());

        if(request.getCarNumber() != null){
            body.add("user_mobile", request.getUserMobile());
        }
        if(request.getCarNumber() != null) {
            body.add("car_number", request.getCarNumber());
        }
        if (request.getUserMobile() != null){
            body.add("user_name", request.getUserName());
        }
        return sendRequest(BASE_URL_CREATE_ORDER, body, CreateOrderVO.class);
    }

    /**
     * 申请退款
     * @param request
     * @return
     */
    @PostMapping("/applyRefund")
    public ResponseData applyRefund(@RequestBody KstOrderDto request) {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("order_number", request.getOrderNumber());
        body.add("refund_remark", request.getRefundRemark());
        body.add("out_trade_no", request.getOutTradeNo());
        return sendRequest(BASE_URL_APPLY_REFUND, body, CreateOrderVO.class);
    }


    /**
     * 获取司机信息
     */
    @RequestMapping("/getDriver")
    public ResponseData getDriver() {
        User user = userAop.getUser();
        QueryWrapper<BasicDriver> basicDriverQueryWrapper = new QueryWrapper<>();
        BasicDriver basicDriver = basicDriverService.getBaseMapper()
                .selectOne(basicDriverQueryWrapper.eq("user_id", user.getUserId()));
        QueryWrapper<BasicPrivatecar> basicPrivatecarQw = new QueryWrapper<>();
        BasicPrivatecar driverDetail = basicPrivatecarService.getBaseMapper().selectOne(basicPrivatecarQw.eq("driver_id1", basicDriver.getId()));
        return ResponseData.success(driverDetail);
    }


    // 发送请求方法抽取
    private <T> ResponseData sendRequest(String url, MultiValueMap<String, String> body, Class<T> responseType) {
        try {
            String requestTime = String.valueOf(System.currentTimeMillis() / 1000L);
            String sign = generateSign(requestTime);
            // 请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("sign", sign);
            headers.set("requestTime", requestTime);

            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);
            ResponseEntity<T> response = restTemplate.postForEntity(url, entity, responseType);

            log.info("转换后响应结果：" + response.getBody());

            return ResponseData.success(response.getBody());
        } catch (Exception e) {
            log.error("请求异常", e);
            return ResponseData.error("请求异常，请稍后重试");
        }
    }




    // 生成签名
    private String generateSign(String requestTime) throws Exception {
        String toBeSigned = signKey + requestTime + signKey;

        MessageDigest md = MessageDigest.getInstance("MD5"); // 使用MD5算法
        byte[] digest = md.digest(toBeSigned.getBytes(StandardCharsets.UTF_8)); // 转换为MD5哈希值

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
